﻿using System;
using System.Net;
using System.Windows;
using ThePresenter.Net.NetCom;
using ThePresenter.Properties;

namespace ThePresenter.Windows
{
	/// <summary>
	/// Interaction logic for ServerSelectionDialog.xaml
	/// </summary>
	public partial class ServerSelectionDialog : Window, IDisposable
	{
		#region Fields

		NetComServerFinder _serverFinder;

		IPEndPoint _endPointResult;

		#endregion

		#region Properties

		public ServerInfoList _AvailableServers
		{
			get { return _serverFinder.AvailableServers; }
		}

		#endregion

		#region Constructors

		/// <summary>
		/// Initializes a new instance of the <see cref="ServerSelectionDialog"/> class.
		/// </summary>
		public ServerSelectionDialog()
		{
			_serverFinder = new NetComServerFinder();
		}

		#endregion

		#region Methods

		public IPEndPoint SelectServerDialog()
		{
			_serverFinder.BeginSearch(Settings.Default.DefaultApplicationPort);

			InitializeComponent();

			bool? result = this.ShowDialog();

			_serverFinder.EndSearch();

			if (result == true)
			{
				return _endPointResult;
			}
			else
			{
				return null;
			}
		}

		private void ConnectButton_Click(object sender, RoutedEventArgs e)
		{
			if (ServerSelector.SelectedItem != null || TryParseIPEndPoint(IPTextBox.Text, out _endPointResult))
			{
				if (ServerSelector.SelectedItem != null)
				{
					_endPointResult = ((ServerInfo)ServerSelector.SelectedItem).ServerEndPoint;
				}

				this.DialogResult = true;
				this.Close();
			}
			else if (IPTextBox.Text != String.Empty)
			{
				MessageBox.Show(Properties.Resources.ServerSelection_InvalidIPFormat);
			}
			else
			{
				MessageBox.Show(Properties.Resources.ServerSelection_MissingSelection);
			}
		}

		private static bool TryParseIPEndPoint(String text, out IPEndPoint endPoint)
		{
			// Assign out value
			endPoint = null;

			IPAddress ip;
			short port;
			String ipText, portText;

			if (string.IsNullOrEmpty(text)) // There is nothing to parse from
			{
				return false;
			}

			if (text.Contains(":")) // IP:Port
			{
				String[] Parts = text.Split(':');

				ipText = Parts[0];
				portText = Parts[1];
			}
			else
			{
				ipText = text; // treat text as IP
				portText = Settings.Default.DefaultApplicationPort.ToString(); // use default Port
			}

			if (IPAddress.TryParse(ipText, out ip) && short.TryParse(portText, out port)) // IP and Port OK
			{
				endPoint = new IPEndPoint(ip, port);

				return true;
			}

			return false;
		}

		/// <summary>
		/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
		/// </summary>
		public void Dispose()
		{
			_serverFinder.Dispose();
		}

		#endregion
	}
}
